package oocl.ita.eordering.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import oocl.ita.eordering.dao.OrderDao;
import oocl.ita.eordering.po.Order;
import oocl.ita.eordering.po.Page;

@Repository("od")
public class OrderDaoImpl implements OrderDao {
	@PersistenceContext(name = "un")
	private EntityManager em;

	@Override
	public int updateOrderStatusToTwo(Integer oId) {
		Order order = em.getReference(Order.class, oId);
		order.setoStatus(2);
		order.setConfirmTime(new Date());
		return 1;
	}

	@Override
	public int updateOrderStatusToFour(Integer oId) {
		Order order = em.getReference(Order.class, oId);
		order.setoStatus(4);
		order.setConfirmTime(new Date());
		order.setFinishTime(new Date());
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> findOrderByStatus(Integer mId, Integer oStatus) {
		String jpql = "from Order o where o.mId=:mId and o.oStatus=:oStatus";
		List<Order> list = em.createQuery(jpql).setParameter("mId", mId).setParameter("oStatus", oStatus)
				.getResultList();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> findHistoryOrders(Integer mId) {
		String jpql = "from Order o where o.mId=:mId and o.oStatus in(2,3,4)";
		List<Order> list = em.createQuery(jpql).setParameter("mId", mId).getResultList();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> findComplaintOrders(Integer mId) {
		String jpql="from Order o where o.mId=:mId and o.complaint is not null";
		List<Order> list=em.createQuery(jpql).setParameter("mId", mId).getResultList();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> pageHistoryOrders(Page p,Integer mId) {
		int s =  p.getStartPage() - 1;
		//String sql = "select * from ( select ROWNUM rn, m.* from ( select * from merchant a left join maudit b on a.mid=b.mid where b.status=1)m where ROWNUM<=? ) where rn >=?";
		String jpql = "from Order o where o.mId=:mId and o.oStatus in(2,3,4)";
		List<Order> list = em.createQuery(jpql).setParameter("mId", mId).setMaxResults(p.getPageSize()).setFirstResult(s).getResultList();
		return list;
	}

	@Override
	public int countHistoryOrders(Integer mId) {
		String jpql = " from Order o where o.mId=:mId";
		int rs = em.createQuery(jpql).setParameter("mId", mId).getResultList().size();
		return rs;
	}
	
	

}
